package saucaca.fragment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.R;
import lemon.kenhnhacvn.VideoPlayActivity;

import org.json.JSONException;

import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.HomeData;
import saucaca.Util.PreferenceUtils;
import saucaca.Util.TagName;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;


public class AccountLoginDialog extends DialogFragment {
	String TAG=AccountLoginDialog.class.getName();
	
	ViewGroup rootView;
	VideoPlayActivity context;
	LinearLayout btnFacebook, btnGoogle, btnLogin;
	String user, pass;
	Resources resources;
	EditText edtUser, edtPass;

	boolean isFacebook = false;
	private UiLifecycleHelper uiHelper;
	
	AccountManager mAccountManager;
	String token;
	int serverCode;
	private static final String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";
	String GOOGLE_USER_DATA;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context=(VideoPlayActivity) getActivity();
		initViewsSetting();
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.login).setView(rootView).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dismiss();
			}
		}).create();
		return dialog;
	}

	private void initViewsSetting() {
		LayoutInflater inflater = LayoutInflater.from(getActivity());
		rootView = (ViewGroup) inflater.inflate(R.layout.account_login_dialog, null, false);
		btnLogin = (LinearLayout) rootView.findViewById(R.id.login_btnLinear_loginButton);
		btnFacebook = (LinearLayout) rootView.findViewById(R.id.login_btnLinear_loginFacebook);
		btnGoogle = (LinearLayout) rootView.findViewById(R.id.login_btnLinear_loginGoogle);
		edtUser = (EditText) rootView.findViewById(R.id.login_edt_username);
		edtPass = (EditText) rootView.findViewById(R.id.login_edt_password);

		btnLogin.setOnClickListener(clickListener);
		btnFacebook.setOnClickListener(clickListener);
		btnGoogle.setOnClickListener(clickListener);
		
		LoginButton authButton = (LoginButton) rootView.findViewById(R.id.authButton);
		authButton.setFragment(this);
		authButton.setReadPermissions(Arrays.asList("email", "user_status"));
	}
	public void dismiss(){
		getDialog().dismiss();
	}
	View.OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			isFacebook = false;
			switch (v.getId()) {
				case R.id.login_btnLinear_loginButton:
					Login();
					break;
				case R.id.login_btnLinear_loginFacebook:
					isFacebook = true;
					loginFacebook();
					break;
				case R.id.login_btnLinear_loginGoogle:
					syncGoogleAccount();
					break;

				default:
					break;
			}
		}
	};
	private void Login() {
		user = edtUser.getText().toString();
		pass = edtPass.getText().toString();
		if (!user.equals("") && !pass.equals("")) {
			new GetFromServices().execute("");
		}
	}

	class GetFromServices extends AsyncTask<String, String, String> {
		ProgressDialog progressDialog = new ProgressDialog(getActivity());

		@Override
		protected String doInBackground(String... param) {
			String str = WServiceLib.login(user, pass);
			BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (!progressDialog.isShowing())
				progressDialog.show();
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (progressDialog.isShowing())
				progressDialog.hide();
			if (result != null) {
				try {
					JsonReader.loginReader(result);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			if (HomeData.headerObject.getCODE().equals("0")) {
				ImageLoader.getInstance().loadImage(HomeData.homeAccount.getAVATAR(), new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
						super.onLoadingComplete(imageUri, view, loadedImage);
						PreferenceUtils.putString(context, TagName.KeyPreference_fullname, HomeData.homeAccount.getFULL_NAME());
						PreferenceUtils.putString(context, TagName.KeyPreference_usercode, HomeData.homeAccount.getUSER_CODE());
						PreferenceUtils.putString(context, TagName.KeyPreference_sex, HomeData.homeAccount.getSEX());
						PreferenceUtils.putString(context, TagName.KeyPreference_birthday, HomeData.homeAccount.getBIRTH_DAY());
						PreferenceUtils.putString(context, TagName.KeyPreference_user, HomeData.homeAccount.getUSER_NAME());
						PreferenceUtils.putString(context, TagName.KeyPreference_pass, edtPass.getText().toString());
//						PreferenceUtils.putString(context, TagName.KeyPreference_phone,HomeData.homeAccount.getMOBILE());
						PreferenceUtils.putString(context, TagName.KeyPreference_avatar, BaseEngine.BitmapTobase64(loadedImage));
						TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
						dismiss();
					}
				});
			} else
				TagName.showToastShort(context, HomeData.headerObject.getMESSAGE());
		}
	}

	public void loginFacebook() {
		Session.openActiveSession(context, true, new Session.StatusCallback() {
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if (session.isOpened()) {
					Log.e("getAccessToken", session.getAccessToken());

					Request.newMeRequest(session, new Request.GraphUserCallback() {
						@Override
						public void onCompleted(GraphUser user, Response response) {
							System.out.println("------------>Complete");
						}
					}).executeAsync();
				} else {
					Log.e("Login", "Lỗi không kết nối được facebook!");
				}
			}
		});
	}
	

	// Called when session changes
		private Session.StatusCallback callback = new Session.StatusCallback() {
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				onSessionStateChange(session, state, exception);
			}
		};

		// When session is changed, this method is called from callback method
		private void onSessionStateChange(Session session, SessionState state, Exception exception) {

			if (state.isOpened()) {
				Log.i(TAG, "Logged in...");
				// make request to the /me API to get Graph user
				TagName.showLogError(TAG, "Access Token: " + session.getAccessToken());
				Request.newMeRequest(session, new Request.GraphUserCallback() {

					// callback after Graph API response with user
					// object
					@Override
					public void onCompleted(GraphUser user, Response response) {
						if (user != null) {
							// Set User name
							TagName.showLogError(TAG, "User: " + user);
							TagName.showLogError(TAG, "Hello: " + user.getName());
							String id = user.getProperty("id").toString();
							TagName.showLogError(TAG, "Your Id: " + id);
							TagName.showLogError(TAG, "Your Email: " + user.getProperty("email").toString());
							// ImageView user_picture;
							// userpicture=(ImageView)findViewById(R.id.userpicture);
							URL img_value = null;
							try {
								img_value = new URL("http://graph.facebook.com/" + id + "/picture?type=large");
								TagName.showLogError(TAG, "Your avatar: " + img_value);
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// Bitmap mIcon1 =
							// BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
							// userpicture.setImageBitmap(mIcon1);
							dismiss();
						}
					}
				}).executeAsync();
			} else if (state.isClosed()) {
				Log.i(TAG, "Logged out...");
			}
		}

		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			try {
				uiHelper.onActivityResult(requestCode, resultCode, data);
				Log.i(TAG, "OnActivityResult...");

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onResume() {
			super.onResume();
			try {
				uiHelper.onResume();
			} catch (Exception e) {
			}
		}

		@Override
		public void onPause() {
			super.onPause();
			try {
				uiHelper.onPause();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		@Override
		public void onDestroy() {
			super.onDestroy();
			try {
				uiHelper.onDestroy();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		@Override
		public void onSaveInstanceState(Bundle outState) {
			super.onSaveInstanceState(outState);
			try {
				uiHelper.onSaveInstanceState(outState);
			} catch (Exception e) {
			}
		}

	// Google ...
	private String[] getAccountNames() {
		mAccountManager = AccountManager.get(context);
		Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
		}
		return names;
	}

	// Google ...
	public void syncGoogleAccount() {
		if (isNetworkAvailable() == true) {
			String[] accountarrs = getAccountNames();
			if (accountarrs.length > 0) {
				// you can set here account for login
				new GetGoogleAccount(context, accountarrs[0], SCOPE).execute();
			} else {
				Toast.makeText(context, "No Google Account Sync!", Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(context, "No Network Service!", Toast.LENGTH_SHORT).show();
		}
	}

	// Google ...
	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			Log.e("Network Testing", "***Available***");
			return true;
		}
		Log.e("Network Testing", "***Not Available***");
		return false;
	}

	class GetGoogleAccount extends AsyncTask<Void, Void, Void> {
		protected VideoPlayActivity context;
		protected String mScope;
		protected String mEmail;
		String TAG = "TokenInfoTask";

		GetGoogleAccount(VideoPlayActivity activity, String email, String scope) {
			this.context = activity;
			this.mScope = scope;
			this.mEmail = email;
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				fetchNameFromProfileServer(context, mEmail, mScope);
			} catch (IOException ex) {
				onError("Following Error occured, please try again. " + ex.getMessage(), ex);
			} catch (JSONException e) {
				onError("Bad response: " + e.getMessage(), e);
			}
			return null;
		}

		private void fetchNameFromProfileServer(VideoPlayActivity context, String mEmail, String mScope) throws IOException, JSONException {
			String token = fetchToken(context, mEmail, mScope);
			URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			int sc = con.getResponseCode();
			if (sc == 200) {
				InputStream is = con.getInputStream();
				GOOGLE_USER_DATA = readResponse(is);
				Log.e(TAG, GOOGLE_USER_DATA);
				is.close();
				return;
			} else if (sc == 401) {
				GoogleAuthUtil.invalidateToken(context, token);
				onError("Server auth error, please try again.", null);
				return;
			} else {
				onError("Server returned the following error code: " + sc, null);
				return;
			}
		}

		private String readResponse(InputStream is) throws IOException {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] data = new byte[2048];
			int len = 0;
			while ((len = is.read(data, 0, data.length)) >= 0) {
				bos.write(data, 0, len);
			}
			return new String(bos.toByteArray(), "UTF-8");
		}

		protected void onError(String msg, Exception e) {
			if (e != null) {
				Log.e(TAG, "Exception: ", e);
			}
		}

		int mRequestCode;

		protected String fetchToken(VideoPlayActivity context, String mEmail, String mScope) throws IOException {
			try {
				return GoogleAuthUtil.getToken(context, mEmail, mScope);
			} catch (GooglePlayServicesAvailabilityException playEx) {
				// GooglePlayServices.apk is either old, disabled, or not
				// present.
			} catch (UserRecoverableAuthException userRecoverableException) {
				// Unable to authenticate, but the user can fix this.
				// Forward the user to the appropriate activity.
				context.startActivityForResult(userRecoverableException.getIntent(), mRequestCode);
			} catch (GoogleAuthException fatalException) {
				onError("Unrecoverable error " + fatalException.getMessage(), fatalException);
			}
			return null;
		}
	}

	
}
